<script lang="ts" setup>
	import { ref, onMounted, computed } from 'vue';
	import { getAllTeacehrs, getAllTeacehrsPage, getTeacehr, createAppoint, getQuestions, getAdvisorys, getAdvisorysByTime } from '@/api/psychology/appointment.js'
	import { getUserList } from '@/api/school.js'
	import { userInfo } from '@/store/Pinia/userInfo.js'
	import { onNavigationBarButtonTap } from '@dcloudio/uni-app'
	import TnButton from '../../node_modules/@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
	import TnPopup from '../../node_modules/@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
	import TnTag from '../../node_modules/@tuniao/tnui-vue3-uniapp/components/tag/src/tag.vue'
	import TnEmpty from '../../node_modules/@tuniao/tnui-vue3-uniapp/components/empty/src/empty.vue'
	import { it } from 'element-plus/es/locale';

	const cates = ["选择时间预约", "选择老师预约"]

	let curNow = ref('0');
	let timeShow = ref(true);
	let teachers = ref<any[]>([]);
	let theTeacher = ref({});
	let allQuestions = ref({});
	let time = ref('');
	let number = ref('');
	let an1 = ref();
	let an2 = ref();
	let an3 = ref();
	const answers = ref<any[]>([]);
	const littleShowPopup = ref(false)
	const showPopup = ref(false)
	let fullDate = ref();
	const userInfoModel = userInfo()


	onMounted(() => {
		const currentDate = new Date(); // 获取当前日期
		const year = currentDate.getFullYear(); // 获取年份
		const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
		const day = String(currentDate.getDate()).padStart(2, '0'); // 获取日期，并补零
		fullDate.value = `${year}-${month}-${day}`;
		// fullDate.value = ""
		selectDate.value = fullDate.value
		getAll(fullDate.value);

	});

	//分页方法
	const current = ref(0)
	const totalData = ref(0)
	const pageSize = ref(12)
	const pageNum = computed(() => {
		return Math.ceil(totalData.value / pageSize.value)
	})
	const pageList = computed(() => {
		let list = []
		for (let i = 1; i <= pageNum.value; i++) {
			list.push(i);
		}
		return [...list]
	})
	const pre = () => {
		if (current.value > -2) {
			current.value--
			getAll(selectDate.value)
		}
	}
	const next = () => {
		current.value++
		getAll(selectDate.value)

	}

	const getAll = (time = null) => {
		let item = {
			"workDate": time,
			current: current.value + 1,
			size: pageSize.value
		}
		getAllTeacehrsPage(item).then((res) => {
			teachers.value = res.data.data.records;
			totalData.value = res.data.data.total;
		}).catch((error) => {
		})
	};

	// 自动保存 
	const exit = () => {
		littleShowPopup.value = true;
	}
	const goBack = () => {
		littleShowPopup.value = false;
	}

	interface answersList {
		an1 ?: String,
		an2 ?: String,
		an3 ?: String,
	}

	interface createItem {
		"cnId" ?: String | number,
		"stuId" ?: String,
		"consRoomId" ?: String,
		"reservationDate" ?: String,
		"reservationEndTime" ?: String,
		"reservationStartTime" ?: String,
		"consAdvisoryState" ?: String,
		"stuPhone" ?: String,
		"problemList" ?: any,
		"consCnDutyId" ?: String | number
	}

	const createItem = ref<createItem>({})
	const answersObj = ref<answersList>({})
	const no = () => {
		selectTimeId.value = null
		littleShowPopup.value = false;
		showPopup.value = false;
		createItem.value = {}
	}

	const objReduce = computed(() => {//将对象列表中，每个对象的某个属性提出来作为key值，并且重复的合并
		return function (obj, keyName) {
			let groupedObject = obj.reduce((accumulator, currentObject) => {
				const key = currentObject[keyName];
				// 如果当前key还不存在，创建一个新数组
				if (!accumulator[key]) {
					accumulator[key] = [];
				}
				// 将当前对象添加到对应的数组中
				accumulator[key].push(currentObject);
				return accumulator;
			}, {});
			return groupedObject;
		}
	})

	const selectDate = ref('')
	const sectionChange = (index : any) => {
		curNow.value = index;
		if (index == 0) {
			timeShow.value = true;
		} else {
			uni.navigateTo({
				url: '/pages/appointment/apmByCnUser/apmByCnUser'
			})
		}
	}

	const selectedChange = (e) => {
		fullDate.value = e.fullDate;
		getAll(fullDate.value)

	}

	let isEmpty = computed<boolean>(() => {
		return teachers.value.every((teacher : any) => teacher.date !== fullDate.value);
	});

	const teacherList = computed(() => {
		let it = []
		it = teachers.value.filter((item) => {

			if (item.cnUser != null) {
				return item
			}
		})
		return [...it]
	})

	const getTime = computed(() => {
		return function (time) {
			if (time != void 0) {
				var dateObject = new Date(time);

				var timeString = dateObject.toLocaleTimeString('zh', { hour12: false });

				return `${dateObject.getHours()}:${(dateObject.getMinutes() < 10 ? '0' : '') + dateObject.getMinutes()}:00`
			} else {
				return time
			}
		}
	})

	const formmatTime = computed(() => {//将2023-12-14转换成12/14
		return function (tiem) {
			let dateString = tiem;

			// 创建日期对象
			let dateObject = new Date(dateString);

			// 提取月份和日期
			let month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始，所以需要加1
			let day = dateObject.getDate().toString().padStart(2, '0');

			// 创建新的格式
			let newFormat = `${month}/${day}`;
			return newFormat
		}
	})


	const calendarShow = ref(false)
	const schedulingList = ref([])
	const schedulingListLen = ref(0)
	const setDateConfiem = (e) => {
		selectDate.value = e[0]
		let item = {
			"cnId": theTeacher.value.cnUser?.id,
			"workDate": selectDate.value
		}

		theTeacher.value.workDate = selectDate.value
		getAdvisorysByTime(item).then((res) => {
			schedulingList.value = res.data.data
			calendarShow.value = false
		})
	}

	const selectTimeId = ref(0)
	const selectTimeValue = ref('')
	const selectTime = (e) => {
		selectTimeId.value = e.id
		theTeacher.value = e
	}

	const toAppoint = (item) => {
		uni.navigateTo({
			url: '/pages/appointment/apmForm/apmForm?id=' + item.id
		})
	}

	const backToMain = () => {
		uni.reLaunch({
			url: '/pages/index/home/home'
		})
	}

	const flagTest = ref(false)
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
	<articleTable ref="timer"></articleTable>
	<!-- <tabbar style="position: sticky;top: -1px;z-index: 999;"></tabbar> -->
	<Navigator :fixed="true" background-color="#fa973a" status-bar left-icon="back" left-text="返回" title="心理预约"
		@clickLeft="backToMain" customLeft>
	</Navigator>

	<top-banner :classTitle="'心理预约'" :enClassTitle="'RESERVATION'"></top-banner>
	<view @touchend="handleEnd" class="wh100p flex-center">
		<view class="flex-column select-body">

			<view class=" consultant-tabs w100p">
				<view class="gui-dark-bg-level-3  gui-margin-top w100p">
					<view class="gui-flex gui-rows gui-margin-top w100p"
						style="align-items: center;justify-content: space-between">
						<view style="width:500rpx;">
							<gui-segmented-control :items="cates" :current="curNow" borderRadius="50rpx"
								customStyle="border-radius:50rpx;" @change="sectionChange"></gui-segmented-control>
						</view>
						<view class="ml24">
							<view class="flex column-center" @click="flagTest = !flagTest">
								<view class="font20 mr16">{{fullDate}}</view>
								<button type="default" class="gui-button gui-bg-primary gui-noborder vAlign-center "
									style="border-radius:50rpx;height:35px;">
									<text class="gui-icons gui-color-white gui-button-text "
										style="padding:0 20px"><text
											style="margin-right:10px;line-height:35px">请选择日期</text>&#xe6d1; </text>
								</button>
							</view>
							<uni-transition ref="ani" custom-class="transition" :mode-class="'fade'"
								class="bgfffff calendar-outBox absolute mt14" :show="flagTest">
								<view class=" flex-column">
									<view class="w100p flex-end " @click="flagTest = false">
										<view style="padding: 0 10px;">
											<u-icon name="close" color="#2979ff" size="18"></u-icon>
										</view>
									</view>
									<view class="calendar-box pt12">
										<zzx-calendar v-show=" true" @selected-change="selectedChange"
											v-if="timeShow"></zzx-calendar>
									</view>
								</view>
							</uni-transition>
						</view>
					</view>
				</view>
			</view>

			<view class="w100p bgfffff consultant-list-box flex-column "
				style="height: 85%;box-sizing: border-box;justify-content: center;min-height: 690px;">

				<gui-empty v-if="teacherList.length<1">
					<template v-slot:img>
						<view class="gui-flex gui-rows gui-justify-content-center">
							<text class="gui-icons gui-empty-icon gui-color-gray font64">&#xe644;</text>
						</view>
					</template>
					<template v-slot:text>
						<text class=" gui-block gui-text-center gui-margin-top gui-color-gray font32">暂无数据</text>
					</template>
				</gui-empty>

				<view v-else class="consultant-list flex-center wh100p" style="align-content: flex-start;">
					<view v-for="(item,index) of teacherList" :key="index"
						style="width: 24%;margin-left: 5px; min-width: 300px;height: 200px;">
						<uni-card v-if="item.cnUser!=null" style="border-radius: 15rpx;margin: 5px;height: 180px;"
							@click=" item?.consCnDutyState==1? '' : toAppoint(item)" class="click consultant-item">
							<view class="gui-card-view gui-margin-top">
								<view class="gui-card-body gui-border-b gui-flex gui-rows gui-nowrap"
									style="padding-bottom:5px ;">
									<view class="flex w100p">
										<view>
											<image class="avatar"
												:src="item?.cnUser?.avatar??'../../static/img/bigavatar.png'"
												mode="aspectFill">
											</image>
										</view>
										<view class="flex-column" style="padding:0rpx 0 0 10px;flex: 1;">
											<view class="flex-between">
												<text class="cnName colorED7B2F"
													style="font-size: 12px;font-weight: 600;line-height: 40rpx;"
													v-show="item?.workStartTime!=void 0 && curNow!=1">时间段：{{getTime(item?.workStartTime)}}-{{getTime(item?.workEndTime)}}</text>
												<text class="cnName colorED7B2F"
													style="font-size: 12px;font-weight: 600;line-height: 40rpx;"
													v-show="item?.workStartTime!=void 0 && curNow!=1">{{item?.consCnDutyState==1?'无名额':'可预定'}}</text>
											</view>
											<view class="flex">
												<text class="cnName"
													style="font-size: 32rpx;font-weight: 600;line-height: 50rpx;">{{item?.cnUser?.realName??'暂无'}}</text>
												<text class="cnName ml24"
													style="font-size: 26rpx;font-weight: 600;line-height: 50rpx;">{{item?.cnUser?.sex ?? '不详'}}</text>
											</view>
											<view v-show="curNow!=1" class="flex" style="line-height: 40rpx;">
												<text class="gui-card-text gui-block gui-third-text">地址：</text>
												<text
													class="gui-card-text gui-block gui-third-text ml14">{{item?.consRoom?.name||'暂无'}}</text>
											</view>
											<view v-show="curNow==1" class="flex-between" style="line-height: 60rpx;">
												<text class="gui-card-text gui-block gui-third-text">电话：</text>
												<text
													class="gui-card-text gui-block gui-third-text">{{item?.cnUser?.phone??'暂无'}}</text>
											</view>
										</view>
									</view>
								</view>
							</view>
							<view class="pa10" style="height:58px;overflow: hidden;">
								<text class="uni-body"
									style="text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 3;-webkit-box-orient: vertical;">简介：{{item?.cnUser?.remark??'老师温柔体贴，有不开心的事情就来向我倾诉吧。'}}</text>
							</view>
						</uni-card>
					</view>
					<i v-for="(item,index) of 5" :key="index" style="width: 24%;margin-left: 5px;min-width: 300px;"></i>
				</view>

				<view class="w100p flex-center" style="padding-top: 20px;">
					<pagination :current="current" :pageList="pageList" :pageSize="12" :totalData="totalData"
						@nextPage="next" @prePage="pre"></pagination>

				</view>
			</view>

		</view>

	</view>

</template>

<style>
	.select-body {
		width: 1400px;
	}

	.select-body .consultant-tabs {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-align: center;
		-ms-flex-align: center;
		align-items: center;
		height: 40px;
		margin-bottom: 30px;
	}

	.select-body .consultant-list-box {
		padding: 15px 78px 0;
	}

	.header1 {
		height: 50rpx;
		width: 100%;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
	}

	/deep/.custom .zzx-calendar .calendar-days {
		height: 80%;
	}

	/deep/.custom .zzx-calendar .calendar-days .calendar-day {
		height: 50px;
	}

	.consultant-list {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	.consultant-item {
		background: linear-gradient(164deg, rgba(255, 211, 161, 0.3)15%, rgba(255, 255, 255, 1.0)50%, rgba(255, 255, 255, 1.0)60%);
	}

	.select-body .consultant-list-box {
		padding: 15px 15px 30px;
	}

	.calendar-outBox {
		width: 330px;
		height: 330px;
		padding: 10px;
		z-index: 99;
		transition-duration: 1s;
		box-shadow: 0px 4px 20px 0px rgba(65, 122, 231, 0.30);
		backdrop-filter: blur(11px);
	}

	.calendar-box {
		width: 300px;
		height: 300px;
		margin: 0 auto;
		transition-duration: 1s;
	}

	.el-pager {
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
		list-style: none;
		font-size: 0;

	}

	.el-pager li {
		height: 30px;
		line-height: 30px;
		font-size: 14px;
		color: #606266;
		min-width: auto;
		width: 25px;
		padding: 0;
		font-weight: 400;
		margin-right: 4px;
		text-align: center;
		transition-duration: 0.2s;
	}

	.el-pager li.active {
		background: #027dee;
		border-radius: 2px;
		color: #fff !important;
	}
</style>